﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Reflection;

namespace HQWeb.Progect.PhotoManage.SelectProject
{
    public partial class MangerList : BasePage
    {
        #region 全局变量

        private static DataTable data;
        private static DataTable imageData;
        private static bool flag = true;

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            //VerdictIsLogin();
            if (!IsPostBack)
            {
                BianDropList();    //绑定分店
                CheckUser();
                GetData();
                BianGV1();
            }
        }

        #region 用户权限判断

        private void CheckUser()
        {
            //if (Convert.ToBoolean(Session["IsAll"]) == false)
            //{
                LabTile.Style["display"] = "none";
                drop_Branch.Style["display"] = "none";
                flag = false;
            //}
            string strBID = Session["BRANCH_ID"].ToString();
            drop_Branch.SelectedValue = strBID;
            if (Request["id"] != null)
            {
                txtPIdHid.Text = Request["id"].Trim();
            }
        }

        #endregion

        #region 绑定下拉列表框

        private void BianDropList()
        {
            BLL.SysManage.T_PUB_BRANCH branchBll = new BLL.SysManage.T_PUB_BRANCH();
            List<Model.SysManage.T_PUB_BRANCH> branchModel = branchBll.GetModelList("");
            drop_Branch.DataSource = branchModel;
            drop_Branch.DataTextField = "BRANCH_NAME"; //dropdownlist的Text的字段 
            drop_Branch.DataValueField = "BRANCH_ID";//dropdownlist的Value的字段 
            drop_Branch.DataBind();
            ListItem item = new ListItem("全部", "");
            item.Selected = true;
            drop_Branch.Items.Add(item);

        }

        #endregion

        #region 数据绑定

        /// <summary>
        /// 得到所有数据源
        /// </summary>
        private void GetData()
        {
            BLL.Progect.T_PUB_PROJECT bll = new BLL.Progect.T_PUB_PROJECT();
            DataSet ds = bll.GetListWithMateralAndImage(txtPIdHid.Text, drop_Branch.SelectedValue);
            data = ds.Tables[0];
            imageData = ds.Tables[1];
        }

        //主表数据绑定
        private void BianGV1()
        {
            string strName = txtName.Text.Trim();
            DataTable datable = new DataTable();

            if (strName != "")
            {
                var dataSource = (from v in data.AsEnumerable() where v.Field<string>("PROJECT_NAME").Contains(strName) select new { a = v.Field<string>("PROJECT_ID"), b = v.Field<string>("PROJECT_NAME"), c = v.Field<int?>("PRICE"), d = v.Field<string>("BRANCH_NAME") }).Distinct();
                datable = ConvertToTable(dataSource);
            }
            else
            {
                var dataSource = (from v in data.AsEnumerable() select new { a = v.Field<string>("PROJECT_ID"), b = v.Field<string>("PROJECT_NAME"), c = v.Field<int?>("PRICE"), d = v.Field<string>("BRANCH_NAME") }).Distinct();
                datable = ConvertToTable(dataSource);
            }
            if (datable.Rows.Count > 0)
            {
                AddUrl(datable, imageData);
                GridView1.DataSource = datable;
                GridView1.DataBind();
            }
            else
            {
                GridView1.DataSource = null;
                GridView1.DataBind();
            }
        }


        //添加项目图片路径和数量    
        private void AddUrl(DataTable dt, DataTable urldt)
        {
            dt.Columns.Add("URLThumbnail", typeof(string));
            dt.Columns.Add("URLOriginal", typeof(string));
            dt.Columns.Add("TYPE", typeof(string));
            dt.Columns.Add("Number", typeof(string));
            int dtCount = dt.Rows.Count;
            DataRow[] dataRows;
            DataRow rowTemp;
            string strType = "";
            string strUrl = "";
            for (int i = 0; i < dtCount; i++)
            {
                rowTemp = dt.Rows[i];
                string strRowID = rowTemp["a"].ToString();
                dataRows = urldt.Select(string.Format(" PROJECT_ID='{0}'", rowTemp["a"]));
                if (dataRows.Length > 0)
                {
                    strType = dataRows[0]["TYPE"].ToString();
                    if (strType == "1")
                    {
                        strUrl = dataRows[0]["URLThumbnail"].ToString();
                    }
                    else
                    {
                        strUrl = dataRows[0]["URLThumbnail"].ToString();
                    }
                    rowTemp["URLThumbnail"] = "../../../" + strUrl.Replace("//", "/");
                    // rowTemp["URLOriginal"] = dataRows[0]["URLOriginal"];
                    rowTemp["TYPE"] = strType;
                }
                else
                {
                    rowTemp["URLThumbnail"] = "";
                    // rowTemp["URLOriginal"] = "";
                    rowTemp["TYPE"] = "";
                }
            }
        }
        /// <summary>
        /// 转化为datatable
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        private DataTable ConvertToTable(IEnumerable<object> query)
        {
            DataTable dtList = new DataTable();
            bool isAdd = false;
            PropertyInfo[] objProterties = null;
            foreach (var item in query)
            {
                if (!isAdd)
                {
                    objProterties = item.GetType().GetProperties();
                    foreach (var itemProterty in objProterties)
                    {
                        Type type = null;
                        if (itemProterty.PropertyType != typeof(string) && itemProterty.PropertyType != typeof(int) && itemProterty.PropertyType != typeof(DateTime))
                        {
                            type = typeof(string);
                        }
                        else
                        {
                            type = itemProterty.PropertyType;
                        }
                        dtList.Columns.Add(itemProterty.Name, type);
                    }
                    isAdd = true;
                }
                var row = dtList.NewRow();
                foreach (var pi in objProterties)
                {
                    row[pi.Name] = pi.GetValue(item, null);
                }
                dtList.Rows.Add(row);
            }

            return dtList;
        }


        /// <summary>
        /// 显示子表数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            GridViewRow row = e.Row;
            if (row.DataItem == null)
            {
                return;
            }
            GridView gv = new GridView();
            gv = (GridView)row.FindControl("GridView2");
            if (string.IsNullOrEmpty(gv.UniqueID))
            {
                gv.PageIndex = 0;
                gv.EditIndex = -1;
                ClientScript.RegisterStartupScript(GetType(), "Expand", "<SCRIPT LANGUAGE='javascript'>expandcollapse('div" + ((DataRowView)e.Row.DataItem)["a"].ToString() + "','one');</script>");
            }
            try
            {
                string strPid = Convert.ToString(((DataRowView)e.Row.DataItem)["a"]);
                DataTable ds = new DataTable();
                var dataSource = (from v in data.AsEnumerable() where v.Field<string>("PROJECT_ID") == strPid select new { a = v.Field<int?>("ID"), b = v.Field<int?>("NUM"), c = v.Field<string>("MATERIAL_NAME") }).Distinct();
                if (dataSource.All(p => p.a != null))
                {
                    ds = ConvertToTable(dataSource);
                    if (ds.Rows.Count > 0)
                    {
                        gv.DataSource = ds.DefaultView;
                        gv.DataBind();
                    }
                }
            }
            catch (Exception ex)
            {
                Universal.JS.Alert(ex.Message);
                return;
            }


        }

        #endregion

        #region 编辑删除
        //编辑
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            int index = e.NewEditIndex;
            string strID = GridView1.DataKeys[index].Value.ToString();
            BLL.Progect.T_PUB_PROJECT bll = new BLL.Progect.T_PUB_PROJECT();
            Model.Progect.T_PUB_PROJECT model = new Model.Progect.T_PUB_PROJECT();
            model = bll.GetModel(strID);
            string strJS = "SelectClick('" + model.PROJECT_ID + "', '" + model.PROJECT_NAME + "', '" + model.PRICE + "', '" + model.REMARK + "', '" + model.BUDGET + "', '" + model.PROJECTTYPE_ID + "')";
            Universal.JS.RunJS(strJS);

        }
        /// <summary>
        /// GridView1主表删除操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        //{
        //    try
        //    {
        //        int index = e.RowIndex;
        //        string strID = GridView1.DataKeys[index].Value.ToString();
        //        BLL.Progect.T_PUB_PROJECT bll = new BLL.Progect.T_PUB_PROJECT();
        //        Model.Progect.T_PUB_PROJECT model = bll.GetModel(strID);
        //        model.FLAG = false;
        //        bll.Update(model);
        //        GetData();
        //        BianGV1();
        //    }
        //    catch (Exception ex)
        //    {
        //        Universal.JS.Alert(ex.Message);
        //        return;
        //    }
        //}

        //#region 子表删除操作
        ///// <summary>
        ///// GridView3 子表删除操作
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
        //{
        //    try
        //    {
        //        GridView gvTemp = (GridView)sender;
        //        int row = Convert.ToInt32(e.RowIndex);
        //        int id = Convert.ToInt32(gvTemp.DataKeys[row].Value);
        //        BLL.Progect.T_PUB_PROJECTMATERIAL bll = new BLL.Progect.T_PUB_PROJECTMATERIAL();
        //        bll.Delete(id);
        //        GetData();
        //        BianGV1();
        //    }
        //    catch (Exception ex)
        //    {
        //        Universal.JS.Alert(ex.Message);
        //        return;
        //    }
        //}
        //#endregion
        #endregion

        #region 翻页事件
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                //strWhere = strWhere.Replace("order by operatetime DESC", "");
                int newPageIndex = 0;

                if (-2 == e.NewPageIndex)
                { // when click the "GO" Button
                    TextBox txtNewPageIndex = null;
                    GridViewRow pagerRow = GridView1.Controls[0].Controls[GridView1.Controls[0].Controls.Count - 1] as GridViewRow; // refer to PagerTemplate
                    //GridViewRow pagerRow = GridView1.BottomPagerRow; //GridView较DataGrid提供了更多的API，获取分页块可以使用BottomPagerRow 或者TopPagerRow，当然还增加了HeaderRow和FooterRow
                    if (null != pagerRow)
                    {
                        txtNewPageIndex = pagerRow.FindControl("txtNewPageIndex") as TextBox;   // refer to the TextBox with the NewPageIndex value
                    }

                    if (null != txtNewPageIndex)
                    {
                        newPageIndex = int.Parse(txtNewPageIndex.Text) - 1; // get the NewPageIndex
                    }

                    newPageIndex = newPageIndex < 0 ? 0 : newPageIndex;
                    newPageIndex = newPageIndex >= GridView1.PageCount ? GridView1.PageCount - 1 : newPageIndex;
                    GridView1.PageIndex = newPageIndex;
                }
                else if (e.NewPageIndex == -1)
                {
                    newPageIndex = 0;
                    GridView1.PageIndex = 0;
                }
                else
                {  // when click the first, last, previous and next Button
                    newPageIndex = e.NewPageIndex;
                    GridView1.PageIndex = e.NewPageIndex;
                }

                // check to prevent form the NewPageIndex out of the range


                BianGV1();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion

        #region 添加查询

        //添加
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            string strUrl = string.Format("../../ProgectManage/ProgectEdit.aspx?TypeID={0}", txtPIdHid.Text.Trim());
            Response.Redirect(strUrl);
        }

        //查询
        protected void bnSearch_Click(object sender, EventArgs e)
        {
            if (flag)
            {
                GetData();
                BianGV1();
            }
            else
            {
                BianGV1();
            }
        }

        #endregion
    }
}